package com.cyh.ThreadAlternatelyRun;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

/**
 * Created by yanhuche on 4/18/2017.
 * 
 * 两个线程，一个线程打印1-52的整数，一个线程打印A-Z的字母
 * 要求打印出来的顺序是：12A34B56C...4950Y5152Z
 * 要求线程间通信
 */
public class Main_ThreadAlternatelyRun {

    private final Logger LOGGER = Logger.getLogger(getClass());
    private volatile LastStatus lastStatus = LastStatus.CHARACTER;
    private Object lock = new Object();

    public static void main(String[] args) {
        new Main_ThreadAlternatelyRun().run();
    }

    private void run() {
        initNumberThread();
        initCharThread();
    }

    private void initNumberThread() {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(() -> {
            try {
                doRun();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void doRun() throws InterruptedException {
        LOGGER.debug("Thread1 begin...");
        for (int x = 1; x <= 10; x += 2) {
            TimeUnit.SECONDS.sleep(2);
            synchronized (lock) {
                LOGGER.debug("Thread1 got lock...");
                while (lastStatus != LastStatus.CHARACTER) {
                    LOGGER.debug("Thread1 wait...");
                    lock.wait();
                }
                LOGGER.debug("--> " + x + "" + (x + 1));
                lastStatus = LastStatus.NUMBER;
                lock.notifyAll();
            }
        }
    }

    private void initCharThread() {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(() -> {
            try {
                doRun2();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void doRun2() throws InterruptedException {
        LOGGER.debug("Thread2 begin...");
        for (char x = 'A'; x <= 'E'; x++) {
            synchronized (lock) {
                LOGGER.debug("Thread2 got lock...");
                while (lastStatus != LastStatus.NUMBER) {
                    LOGGER.debug("Thread2 wait...");
                    lock.wait();
                }
                LOGGER.debug("--> " + x);
                lastStatus = LastStatus.CHARACTER;
                lock.notifyAll();
            }
        }
    }

    enum LastStatus {
        NUMBER, CHARACTER
    }


}
